package top.hmtools.jsCss.jsManager;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import top.hmtools.jsCss.autoConfiguration.JsCssAutoConfiguration;

/**
 * javascript相关操作的controller
 * @author HyboJ
 * 创建日期：2017-9-26下午10:33:07
 */
@Controller
public class JavascriptController {
	
	private final Logger logger = LoggerFactory.getLogger(JavascriptController.class);
	
	@Autowired
	private IJavascriptManager javascriptManager;
	
	@Autowired
	private JsCssAutoConfiguration jsCssProperties;
	
	/**
	 * 获取合并的javascript文件内容
	 * @param request
	 * @param response
	 */
	@RequestMapping("#{'${"+JsCssAutoConfiguration.js_uri+":}'?:'/js'}/{jsNames}/")
	public void getJS(@PathVariable("jsNames")String jsNames,HttpServletRequest request,HttpServletResponse response){
		this.getJS(jsNames, "UTF-8", request, response);
	}

	/**
	 * 获取合并的javascript文件内容
	 * @param request
	 * @param response
	 */
	@RequestMapping("#{'${"+JsCssAutoConfiguration.js_uri+":}'?:'/js'}/{jsNames}/{encoding}")
	public void getJS(@PathVariable("jsNames")String jsNames,@PathVariable("encoding")String encoding,HttpServletRequest request,HttpServletResponse response){
		PrintWriter writer = null;
		try {
			String jsContent = this.javascriptManager.getJs(jsNames);
			response.reset();
			response.setBufferSize(2048);
			response.setCharacterEncoding(encoding);
			response.setContentLength(jsContent.getBytes(encoding).length);
			response.setContentType("application/javascript");
			response.setStatus(HttpServletResponse.SC_OK);
			writer = response.getWriter();
			writer.print(jsContent);
			writer.flush();
		} catch (Exception e) {
			this.logger.error("获取js文件失败："+e.getMessage(),e);
			try {
				response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,e.getMessage());
			} catch (IOException e1) {
				this.logger.error(e1.getMessage(),e1);
			}
		}finally{
			if(writer != null){
				writer.close();
			}
		}
	}
	
	/**
	 * 刷新javascript缓存库
	 * @param request
	 * @param response
	 */
	@RequestMapping("#{'${"+JsCssAutoConfiguration.refresh_js_uri+":}'?:'/refresh/js'}")
	public void refreshJS(HttpServletRequest request,HttpServletResponse response){
		PrintWriter writer = null;
		try {
			boolean refresh = this.javascriptManager.refresh();
			
			response.reset();
			writer = response.getWriter();
			writer.println("refresh javascript repertory status is "+refresh);
			writer.flush();
		} catch (Exception e) {
			this.logger.error("刷新js缓存失败："+e.getMessage(),e);
			try {
				response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,e.getMessage());
			} catch (IOException e1) {
				this.logger.error(e1.getMessage(),e1);
			}
		}finally{
			if(writer != null){
				writer.close();
			}
		}
	}
	
	/**
	 * 获取所有javascript缓存库中js文件名
	 * @param request
	 * @param response
	 */
	@RequestMapping("#{'${"+JsCssAutoConfiguration.list_js_uri+":}'?:'/list/js'}")
	public void listJsMenu(HttpServletRequest request,HttpServletResponse response){
		PrintWriter writer = null;
		try {
			List<String> listJsFilenames = this.javascriptManager.listJsFilenames();
			
			response.reset();
			response.setBufferSize(2048);
			response.setCharacterEncoding(this.jsCssProperties.getEncoding());
//			response.setContentLength(jsContent.length());
			response.setContentType("text/html");
			response.setStatus(HttpServletResponse.SC_OK);
			writer = response.getWriter();
			writer.println("<title>JavaScript文件列表（总计："+listJsFilenames.size()+"条）</title>");
			writer.println("<style type=\"text/css\">a:link,a:visited{text-decoration:none;}</style>");
			writer.println("<h4>All javascript file name is (counts:"+listJsFilenames.size()+"):</h4>");
			writer.println("<a href=\""+this.jsCssProperties.getRefreshJsUri()+"\"><h4>Refresh js store</h4></a>");
			writer.println("<table>");
			for(String jsTmp:listJsFilenames){
				writer.println("<tr>");
				writer.println("<td><a href=\""+this.jsCssProperties.getJsUri()+"/"+jsTmp+"/\">"+jsTmp+"</a></td>");
				writer.println("<td><a href=\""+this.jsCssProperties.getJsUri()+"/"+jsTmp+"/UTF-8\">"+"UTF-8"+"</a></td>");
				writer.println("<td>&nbsp;<a href=\""+this.jsCssProperties.getJsUri()+"/"+jsTmp+"/GBK\">"+"GBK"+"</a></td>");
				writer.println("</tr>");
				writer.flush();
			}
			writer.println("</table>");
		} catch (Exception e) {
			this.logger.error("获取js列表失败："+e.getMessage(),e);
			try {
				response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,e.getMessage());
			} catch (IOException e1) {
				this.logger.error(e1.getMessage(),e1);
			}
		}finally{
			if(writer != null){
				writer.close();
			}
		}
	}
}
